/**
 * @author ahammer
 * @date   2009
 */

/*
 * This file is part of Iqm.
 * Copyright (c) 2010-2011 Helmut Ahammer
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package main;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileSystemView;
import tools.WelcomeScreen;

/**
 * Main Iqm class
 */
public class Iqm {
	
	private static final String CURRIQMVERSION = "1.11.001";

	Iqm() throws Exception {
	
		//super();
		//get_lock();
		//Lock Iqm
		/*
		if (IqmTools.checkIfExists("Iqm") == true){
	        System.err.println ("Iqm is already running and locked!");
	        JOptionPane.showMessageDialog (null, "Iqm is already running and locked!", "Information", JOptionPane.INFORMATION_MESSAGE);
	        System.exit (1);
		}	
		*/
		
		
		IqmTools.setIqmVersion (CURRIQMVERSION);
		//IqmTools.setIqmVersion ("");
		IqmTools.setJavaVersionMin("1.6.0_12");
	
		WelcomeScreen welcomeScreen = new WelcomeScreen();
		welcomeScreen.display();

        IqmFrame iqmFrame = new IqmFrame();
		iqmFrame.createAndShowGUI(); 
		Tank.createAndShowGUI();
	    Manager.createAndShowGUI();
		Look.createAndShowGUI();
		Board.createAndShowGUI();
		
		String iqmVersion       = IqmTools.getIqmVersion();
		String javaVersionMin   = IqmTools.getJavaVersionMin();
		String javaVersionInUse = System.getProperty("java.version");
		//System.out.println("Iqm: "+javaVersionInUse.replace("_", "").replace(".",""));
		//System.out.println("Iqm: "+javaVersionMin.replace("_", "").replace(".",""));
		
		Board.appendTexln("Iqm Copyright (c) 2010-2011 Helmut Ahammer");
		Board.appendTexln("Java version in use: "+System.getProperty("java.version"));
		//if (System.getProperty("java.version").substring(0,5).compareTo(JavaVersion)<0) {
		if (javaVersionInUse.replace("_", "").replace(".","").compareTo(javaVersionMin.replace("_", "").replace(".",""))<0) {		
			javax.swing.JOptionPane.showMessageDialog(null,"It is recommended to use Java "+javaVersionMin+" or higher.");
			//javax.swing.JOptionPane.showMessageDialog(null,"Iqm: IQMJ "+iqmVersion+" requires Java "+javaVersionMin+" or later.");
		    //System.exit(0);
        }
		
		
		//default (true) is that ImageIO caches images to disk when they are read!
		ImageIO.setUseCache(false);
	
		//Use of MediaLib acceleration or not
		System.setProperty("com.sun.media.jai.disableMediaLib", "true");
		//JAI 1.1.3 native acceleration problems:
		//SubSampleAverage: sometimes black lines around tiles (Pyramid Dimension)
		//
		//List of all system properties
		//System.getProperties().list(System.out);

		//PlanarImage pi =  JAI.create("url", ClassLoader.getSystemResource("imgs/LogoIqm_v1.0_800x600_Bright.png"));
		PlanarImage pi =  JAI.create("url", ClassLoader.getSystemResource("imgs/LogoIqm_v1.0_800x600_LightGrey.png"));
		//pi.setProperty("file_name", "imgs/LogoIqm_v1.0_800x600_Bright.png");	
		pi.setProperty("file_name", "imgs/LogoIqm_v1.0_800x600_LightGrey.png");	
		pi.setProperty("image_name", " ");	
		Look.setNewImage(pi);

		//iqmFrame.setState(Frame.ICONIFIED); /////???????
		
		//get and set the default image directory	
		//System.out.println("Iqm: default directory :"+FileSystemView.getFileSystemView().getDefaultDirectory().toString());  //Eigene Dateien
		//System.out.println("Iqm: home directory:"+FileSystemView.getFileSystemView().getHomeDirectory().toString());
		//File dir = "./"
		File imgDir = FileSystemView.getFileSystemView().getDefaultDirectory();
		IqmTools.setCurrImgPath(imgDir);
	
		//Delete all file in user temp directory exept iqmDefaultPath.txt
		IqmTools.deleteUserTempFiles();
		IqmTools.deleteUserTempDirs();
		
		//set the default iqm temp directory
		String userHome = System.getProperty("user.home");
		//IqmTools.setUserDefaultDir(new File(userHome));
		
		//userHome = userHome  + File.separator+"Iqm"+File.separator+"IqmTemp";  //for windows OK
		String userIqmDir =     userHome  + IqmTools.getFileSeparator()+"Iqm";
		String userIqmTempDir = userHome  + IqmTools.getFileSeparator()+"Iqm"+ IqmTools.getFileSeparator()+"IqmTemp";
				
		boolean success = new File(userIqmTempDir).mkdirs();
		if (success) {
			Board.appendTexln("Directory: " + userIqmTempDir + " created");
			//IqmTools.setUserDefaultDir(new File(userHome));
		}
		Board.appendTexln("User Iqm directory: "+ userIqmDir);   
		Board.appendTexln("User Iqm temp directory: "+ userIqmTempDir);   
		    
	    //read or create ini file
		File iqmIniFile = new File(userIqmDir+IqmTools.getFileSeparator()+"iqm.ini");	
	    if(iqmIniFile.exists( )){
	        Properties props = new Properties();
	        FileInputStream ins = null;
	        try {
	           ins = new FileInputStream(userIqmDir+IqmTools.getFileSeparator()+"iqm.ini");
               props.load(ins);
	        } catch (IOException e) { 
	        } finally {
	           ins.close();
	        }
	        File currImgPath = new File(props.getProperty("CurrImgPath").toString());
	    	IqmTools.setCurrImgPath(currImgPath);              
	    }else{
		    Properties props = new Properties();
		    props.setProperty("JavaVersion",     System.getProperty("java.version"));
		    props.setProperty("UserIqmDir",      userIqmDir);    
		    props.setProperty("UserIqmTempDir",  userIqmTempDir);    
		    props.setProperty("CurrImgPath",     "");
		     try {
		         // FileOutputStream-Instanz zum Speichern instanzieren
		         FileOutputStream fos = new FileOutputStream(userIqmDir+IqmTools.getFileSeparator()+"iqm.ini");
		         props.store(fos, "Iqm Properties");
		         fos.close();
		      } catch (IOException ignored) {}
	    }
	
	    
	    Board.appendTexln("Current image path: " +IqmTools.getCurrImgPath().toString());
		//initialize all IQM user operators for JAI
		IqmTools.setDefaultToolTipDelays();
		IqmTools.initJAIUserOperators();
		IqmTools.setJAIDefaultOptions(); //TileCache Memory etc..
		
		Board.appendTexln("Iqm started");
	}

	
    /**This is the main Iqm class
     *@param args
     */	
	public static void main(String[] args) {

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				try {
					new Iqm();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
	}
	

}
